<?php
namespace api\modules\v1\models\user;

use api\modules\v1\models\Common;
use api\modules\v1\models\prop\PropUserWarehouse;
use api\modules\v1\models\userLevel\UserLevel;
use api\modules\v1\models\userReceipt\Receipt;
use common\models\CacheKeys;
use common\models\config\ConfigAddress;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\im\Im;
use common\models\Patterns;
use common\models\Sign;
use common\models\Status;
use common\models\user\User;
use common\models\user\UserLoginStatistic;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\StringHelper;

class UserGreet extends \common\models\user\UserGreet
{

    /**
     * 首次登录获取需要打招呼的列表
     * 默认5条数据
     * @return array
     */
    public function getNeedUserList(){
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $levelInfo = UserLevel::getOneInfoById($user['level_id']);
            $where = $andWhere = [];
            $where['is_delete'] = Status::COMMON_RADIO_YES;
            $where['status'] = Status::COMMON_RADIO_YES;
            // 相同喜好
            #1.性别相反
            #2.年龄+-5
            #3.有相同喜好
            #4.按照距离排序
            $where['is_setting'] = Status::COMMON_RADIO_YES;
            switch ($user['sex']) {
                case Status::COMMON_SEX_MAN:
                    $where['sex'] = Status::COMMON_SEX_WOMAN;
                    break;
                case Status::COMMON_SEX_WOMAN:
                    $where['sex'] = Status::COMMON_SEX_MAN;
                    break;
                default:
                    break;
            }

            $andWhere[] = ['<>','id',$user['id']];
            $startAge = date('Y-m-d',strtotime('-5 years', strtotime($user['birthday'])));
            $endAge = date('Y-m-d',strtotime('+5 years', strtotime($user['birthday'])));
            $andWhere[] = ['between','birthday',$startAge,$endAge];

            $interestArr = array_filter(explode(',',trim($user['interests'],',')));
            foreach ($interestArr as $value) {
                $andWhere[] = ['like','interests', $value.','];
            }
//            $longitude = $this->getLongitude() ? $this->getLongitude() : '116.3424590000';
//            $latitude = $this->getLatitude() ? $this->getLatitude() : '39.91024';
            list($longitude,$latitude) = $this->getPosition($user['phone']);

            $distanceField = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$latitude} * PI() / 180 - latitude * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (
                                    {$longitude} * PI() / 180 - longitude * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ),5 
            ) AS distance";
            $accordList = User::getObjectByAndWhere($where,$andWhere, ['id','nick_name','user_face','tx_code','qr_code','signature','sex','birthday','interests','level_id','is_hiding',$distanceField], "distance ASC", 0, 5)->with()->asArray()->all();
            $count = count($accordList);
            $surplusList = [];
            if ($count < 5) {
                $surplusCount = 5 - $count;
                $surplusWhere = $surplusAndWhere = [];
                $surplusAndWhere[] = ['<>','id',$user['id']];
                if ($accordList) {
                    $surplusAndWhere[] = ['<>','id',ArrayHelper::getColumn($list,'id')];
                }


                $surplusList = User::getObjectByAndWhere($surplusWhere,$surplusAndWhere, ['id','nick_name','user_face','tx_code','qr_code','signature','sex','birthday','interests','level_id','is_hiding',$distanceField], "distance ASC", 0, $surplusCount)->with()->asArray()->all();
            }

            $list = array_merge($accordList,$surplusList);
            $result = [];
            foreach ($list as $k => $v) {
                $tmp = [
                    'nick_name' => $v['nick_name'] ?? '',
                    'face' => static::getAvatar($v['user_face']),
                    'tx_code' => $v['tx_code'] ?: '',
                    'sex' => (int) $v['sex'],
                    'age' => $v['birthday'] ? Functions::birthday($v['birthday']) : 0,
                    'distance' => round($v['distance'],2),
//                    'signature' => $v['signature'],
                ];

                $tmp['distance'] = \api\modules\v1\models\user\User::handleDistance($levelInfo, $v, $tmp['distance']);


//                if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO){
//                    $tmp['distance'] = ">100KM";
//                } else {
////                    $tmp['distance'] = $tmp['distance'] ? $tmp['distance'].'KM' : '未知';
//                    $tmp['distance'] = $tmp['distance'].'KM';
//                }

                $sexName = $v['sex'] == Status::COMMON_SEX_MAN ? '他' : '她';

                //是否有相同爱好
                $tmp['tip'] = "{$sexName}可能也对你有兴趣";

                $singleInterestArr = array_filter(explode(',',trim($v['interests'],',')));
                $sameInterest = array_unique(array_intersect($singleInterestArr,$interestArr));
                if ($sameInterest) {
                    $sameInterestStr = trim(implode(',',$sameInterest),',');
                    $tmp['tip'] = "{$sexName}也喜欢{$sameInterestStr}";
                }
                $result[] = $tmp;
            }
            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 打招呼
     * @return array
     */
    public function greet()
    {
        $trans = Yii::$app->db->beginTransaction();
        $user = Yii::$app->getUser()->getIdentity()->toArray();
        $redis = Yii::$app->redis;
        $redisKey = "GREET_" . $user['id'];
        try {
            $exists = $redis->get($redisKey);
            if($exists){
                throw new Exception('速度太快，请稍后尝试！');
            }

            $redis->set($redisKey, true);

            $txCode = Yii::$app->request->post('tx_code',[]);
            if (!$txCode) {
                throw new Exception('请选择打招呼的用户！');
            }

            $currentLevelInfo = UserLevel::getOneByWhere(['id' => $user['level_id']]);
            $countWhere['user_id'] = $user['id'];
            $countAndWhere[] = ['between','create_time',date('Y-m-d'),date('Y-m-d',strtotime("+1 days"))];
            $greetTodayCount = static::getCountByAndWhere($countWhere,$countAndWhere);

            if ($currentLevelInfo['greet_limit']) {
                if ($greetTodayCount >= $currentLevelInfo['greet_limit']) {
                    throw new Exception('当前级别每日打招呼的上限为'.$currentLevelInfo['greet_limit'].'次！');
                }
            }

            $greetUser = User::getObjectByWhere(['tx_code' => $txCode])->with([
                'isFriend' => function ($q) use ($user) {
                    $q->where(['user_id' => $user['id']])->select(['id','friend_id','user_id']);
                },

                'isGreet' => function ($q) use ($user) {
                    $q->where([
                        'user_id' => $user['id'],
                    ])->select(['id','user_id','greet_user_id']);
                },
            ])->asArray()->all();
            if (empty($greetUser)) {
                throw new Exception('请选择打招呼的用户！');
            }

            $date = date('Y-m-d H:i:s');
            foreach ($greetUser as $key => $value) {
                if (empty($value)) {
                    continue;
                }

                if ($value['id'] == $user['id']) {
                    continue;
                }
                $isFriend = ArrayHelper::getValue($value,'isFriend',[]);
                // 是否是好友  好友不能打招呼
                if (empty($isFriend)) {
                    continue;
                }


                // 是否打过招呼
                $isGreet = ArrayHelper::getValue($value, 'isGreet', []);


                $greetData = [];
                if (empty($isGreet)) {
                    $greetData['user_id'] = $user['id'];
                    $greetData['user_code'] = $user['user_code'];
                    $greetData['user_tx_code'] = $user['tx_code'];
                    $greetData['greet_user_id'] = $value['id'];
                    $greetData['greet_user_code'] = $value['user_code'];
                    $greetData['greet_user_tx_code'] = $value['tx_code'];
                    $greetData['is_read'] = Status::COMMON_RADIO_NO;
                    $greetData['create_time'] = $date;
                    $greetRes = static::insertData($greetData);
                    if ($greetRes === false) {
                        throw new Exception('打招呼失败！');
                    }

                    // 发送自定义消息
                    (new Im()) -> sendSingleText($user['tx_code'],$value['tx_code'],"嗨，可以认识一下吗？");
                } else {
                    $greetData['is_read'] = Status::COMMON_RADIO_NO;
                    $greetData['create_time'] = $date;
                    $greetRes = static::updateData($greetData, ['id' => $isGreet['id']]);
                    if ($greetRes === false) {
                        throw new Exception('打招呼失败！');
                    }
                }

                // 未读数量
                (new FriendApply())->notReadApplyNum($value['id'], 0, $date);
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '打招呼成功！');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        } finally {
            $redis->del($redisKey);
        }
    }


    /**
     * 收到的招呼
     * @return array
     */
    public function getReceiveList(){
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $levelInfo = UserLevel::getOneInfoById([$user['level_id']]);
            $page = (int) Yii::$app->request->post('page',1);
            $size = (int) Yii::$app->request->post('size',20);
            $where = $andWhere = [];

            $where['user_id'] = $user['id'];

            $count = static::getCountByAndWhere($where,$andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $orderSql = "create_time DESC";

//            $longitude = $this->getLongitude() ? $this->getLongitude() : '116.3424590000';
//            $latitude = $this->getLatitude() ? $this->getLatitude() : '39.91024';
            list($longitude,$latitude) = $this->getPosition($user['phone']);

            $list = static::getObjectByAndWhere($where,$andWhere, ['*'], $orderSql, $offset, $size)->with([
                'user' => function ($q) use ($longitude, $latitude) {

                    $distanceField = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$latitude} * PI() / 180 - latitude * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (
                                    {$longitude} * PI() / 180 - longitude * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ),5 
            ) AS distance";
                    $q -> select(['id','nick_name','user_face','tx_code','sex','birthday','latitude','longitude','level_id','is_hiding',$distanceField]);
                },
        ])->asArray()->all();

            // 查询在线状态
            $onLineResult = $list ? (new Im()) -> queryOnlineStatus(ArrayHelper::getColumn($list,'user_tx_code')) : [];
            $result = [];

            foreach ($list as $k => $v) {
                $singleUserInfo = ArrayHelper::getValue($v,'user',[]);
                $tmp = [
                    'nick_name' => $singleUserInfo['nick_name'] ?? '',
                    'face' => static::getAvatar($singleUserInfo['user_face']),
                    'tx_code' => $singleUserInfo['tx_code'] ?: '',
                    'sex' => (int) $singleUserInfo['sex'],
                    'age' => $singleUserInfo['birthday'] ? Functions::birthday($singleUserInfo['birthday']) : 0,
                    'distance' => round($singleUserInfo['distance'],2),
                    'signature' => $singleUserInfo['signature'] ?: '暂无签名',
                    'time' => $v['create_time'],
                    'tip' => "有时间，聊一下吧",
                    'is_online' => false,
                ];

                $tmp['distance'] = \api\modules\v1\models\user\User::handleDistance($levelInfo, $singleUserInfo, $tmp['distance']);

//                if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO){
//                    $tmp['distance'] = ">100KM";
//                } else {
////                    $tmp['distance'] = $tmp['distance'] ? $tmp['distance'].'KM' : '未知';
//                    $tmp['distance'] = $tmp['distance'].'KM';
//                }

                if ($onLineResult) {
                    foreach ($onLineResult as $kk => $vv) {
                        if ($vv['To_Account'] == $v['user_tx_code']) {
                            $tmp['is_online'] = $vv['Status'] == 'Online' ? true : false;
                            continue;
                        }
                    }
                }

                $result[] = $tmp;
            }
            $data['data'] = $result;

            # 设为已读
            static::updateData(['is_read' => Status::COMMON_RADIO_YES],['id' => ArrayHelper::getColumn($list,'id')]);


            // 未读数量
            (new FriendApply())->notReadApplyNum($user['id']);

            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 打招呼
     * @return array
     */
    public function canGreet()
    {
        $trans = Yii::$app->db->beginTransaction();
        $user = Yii::$app->getUser()->getIdentity()->toArray();
        try {

            $txCode = Yii::$app->request->post('tx_code',[]);
            if (!$txCode) {
                throw new Exception('请选择打招呼的用户！');
            }

            $currentLevelInfo = UserLevel::getOneByWhere(['id' => $user['level_id']]);
            $countWhere['user_id'] = $user['id'];
            $countAndWhere[] = ['between','create_time',date('Y-m-d'),date('Y-m-d',strtotime("+1 days"))];
            $greetTodayCount = static::getCountByAndWhere($countWhere,$countAndWhere);

            $data = true;
            if ($currentLevelInfo['greet_limit']) {
                if ($greetTodayCount >= $currentLevelInfo['greet_limit']) {
                    $data = false;
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

}
